package com.bytz.modules.cms.domain.impl.price;

import com.bytz.modules.cms.common.service.CmsCacheService;
import com.bytz.modules.cms.domain.model.price.PriceComputeContext;
import com.bytz.modules.cms.domain.model.price.PriceComputeResult;
import com.bytz.modules.cms.domain.util.PriceComputerUtil;
import com.bytz.modules.cms.productLine.entity.ProductLineLevel;
import com.bytz.modules.cms.reseller.service.IResellerLevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 经销商限制产品计算器，顺序4
 *
 * @author shanxuezhong
 */
@Component
public class ResellerLevelDiscountComputer extends AbstractPriceComputer {

    @Autowired
    private IResellerLevelService resellerLevelService;

    @Autowired
    private CmsCacheService cmsCacheService;

    @Override
    public void doCompute(PriceComputeContext context) {
        ensureResellerLevels(resellerLevelService, context);

        // 找出产品线折扣
        Map<String, String> resellerLevelMap = context.getResellerLevelMap();
        List<String> ids = new ArrayList<>(resellerLevelMap.values());
        Map<String, ProductLineLevel> productLineLevelMap = cmsCacheService.getProductLineLevel(ids);

        for (PriceComputeResult result : context.getResults().values()) {
            if (result.getPrice() != null) {
                Optional<BigDecimal> productLineLevel = Optional.ofNullable(productLineLevelMap.get(result.getProductLineLevelId()))
                        .map(ProductLineLevel::getDiscountRatio);
                if (productLineLevel.isPresent()) {
                    productLineLevel
                            .ifPresent(discountRatio -> {
                                result.setProductLineDiscountRatio(discountRatio);
                                result.setPrice(PriceComputerUtil.scale(result.getPrice().multiply(discountRatio)));
                            });
                } else {
                    //设置没有产品线折扣的对象产品价格为空
                    result.setPrice(null);
                }
            }
        }
    }

    @Override
    public void afterCompute(PriceComputeContext context) {
        // 什么也不用做
    }
}